﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using ExamServer.Models;
using ExamServer.Service;
using Microsoft.AspNetCore.Mvc;

namespace ExamServer.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class MenusController : ControllerBase
    {
        private readonly IRepositoryWrapper wrapper;
        private readonly IMapper mapper;

        public MenusController(IRepositoryWrapper wrapper, IMapper mapper)
        {
            this.wrapper = wrapper;
            this.mapper = mapper;
        }

        [HttpGet]
        public async Task<ActionResult> Get()
        {
            var list = await wrapper.Menus.GetAllAsync();//从数据库中获取所有菜单
            if (list != null)
            {
                var modelList = mapper.Map<IEnumerable<MenusModel>>(list);//将数据映射成MenusModel格式
                var firstList = modelList.Where(x=>x.Pid==0); //此处获得所有一级菜单
                //循环获取其二级子菜单
                foreach(var menu in firstList)
                {
                    menu.children = modelList.Where(x => x.Pid == menu.Id);//此处是获取所有二级菜单
                    foreach(var tmenu in menu.children)
                    {
                        if (modelList.Count(x => x.Pid == tmenu.Id)>0)
                        {
                            tmenu.children = modelList.Where(x => x.Pid == tmenu.Id);
                        }
                    }
                }
                return new JsonResult(firstList);

            }
            return NotFound();

        }
    }
}